package com.lbj.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.lbj.mall.auth.feign.MemberFeign;
import com.lbj.mall.common.constant.APPConstant;
import com.lbj.mall.common.constant.Key;
import com.lbj.mall.common.entity.vo.GiteeVo;
import com.lbj.mall.common.entity.vo.MemberVo;
import com.lbj.mall.common.utils.HttpUtils;
import com.lbj.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/oauth")
@Controller
public class OAuthController {

    @Autowired
    MemberFeign memberFeign;

    /**
     * 微博登录授权后回调
     *
     * @param code 回调后由码云提供
     */
    @GetMapping("/gitee")
    public String giteeLogin(@RequestParam("code") String code, HttpSession session) {

        // 通过code交换token
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        params.put("client_id", Key.GITEE_CLIENT_ID);
        params.put("redirect_uri", Key.GITEE_REDIRECT_URI);
        params.put("client_secret", Key.GITEE_CLIENT_SECRET);
        String json = HttpUtils.doPost("https://gitee.com/oauth/token", params);
        log.info("weiboLogin_json ==> " + json);
        JSONObject jsonObject = JSON.parseObject(json);
        String accessToken = (String) jsonObject.get("access_token");
        String refreshToken = (String) jsonObject.get("refresh_token");

        // accessToken过期了，过期时间为1天，86400s
        if (StringUtils.isEmpty(accessToken)) {
            // 重新刷新数据
            // https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token={refresh_token}
        }

        // 通过 accessToken 拿到用户个人信息
        Map<String, Object> userParams = new HashMap<>();
        userParams.put("access_token", accessToken);
        String userJson = HttpUtils.doGet("https://gitee.com/api/v5/user", userParams);
        JSONObject userObj = JSON.parseObject(userJson);
        Long uid = userObj.getLong("id");
        String nickname = (String) userObj.get("name");
        String avatarUrl = (String) userObj.get("avatar_url");

        R result = memberFeign.giteeLogin(new GiteeVo(uid, nickname, avatarUrl, 1));
        MemberVo memberVo = JSON.parseObject(JSON.toJSONString(result.get("data")), new TypeReference<>() {
        });
        log.info("giteeLogin_memberVo ===> " + memberVo);
        session.setAttribute(APPConstant.SAVE_LOGIN_USER, memberVo);
        return "redirect:http://www.localmall.com";
    }

}
